package utils

import (
	"sync/atomic"
)

// / 测试OK
// /  AtomicDecUint32(&v, 0) // v=5  -> 5
// /  AtomicDecUint32(&v, 1) // v=0  -> 4294967295(FFFFFFFF)
// /  AtomicDecUint32(&v, 1) // v=1  -> 0
// /  AtomicDecUint32(&v, 2) // v=5  -> 3
func AtomicDecUint32(addr *uint32, delta uint32) (new uint32) {
	delta2 := ^(delta - 1)
	return atomic.AddUint32(addr, delta2)
}

type AtomicOpera struct {
	flag int32
}

func NewAtomicOpera() *AtomicOpera {
	rval := &AtomicOpera{}
	return rval
}

func (this *AtomicOpera) TryFlagOn() bool {
	return atomic.CompareAndSwapInt32(&this.flag, 0, 1)
}

func (this *AtomicOpera) TryFlagOff() bool {
	return atomic.CompareAndSwapInt32(&this.flag, 1, 0)
}

func (this *AtomicOpera) FlagOff() bool {
	return atomic.CompareAndSwapInt32(&this.flag, 1, 0)
}
